//
//  Task worker
//  Connects PULL socket to tcp://localhost:5557
//  Collects workloads from ventilator via that socket
//  Connects PUSH socket to tcp://localhost:5558
//  Sends results to sink via that socket
//
package main

import (
	"fmt"
	"os"
	"zmq"
	"strconv"
	"strings"
)

func zmq_main() os.Error {
	context, err := zmq.Init(1)
	if err != nil {
		return err
	}
	defer context.Close()	
	
	receiver,err := context.Socket(zmq.PULL)
	if err != nil {
		return err
	}
	defer receiver.Close()
	err = receiver.Connect("tcp://localhost:5557")
	if err != nil {
		return err
	}
	
	sender,err := context.Socket(zmq.PUSH)
	if err != nil {
		return err
	}
	defer sender.Close()
	err = sender.Connect("tcp://localhost:5558")
	if err != nil {
		return err
	}
	
	for {
		data,err := receiver.Recv(0)
		if err != nil {
			return err
		}
		ar := strings.Split(string(data),":")
		if len(ar) != 2 {
			continue
		}
		fmt.Printf("%s.",ar[0])
		n, err := strconv.Atoi64(ar[1])
		if err != nil {
			return err
		}
		zmq.Sleep(n*1e6)
		err = sender.Send(nil,0)
		if err != nil {
			return err
		}
	}
	return nil	
}

var errch = make(chan os.Error)

func main() {
	fmt.Println("Task worker")
	exit := make(chan bool)
	go func() {
		for {
			err := <-errch
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}
		}
	}()
	go func() {
		err := zmq_main()
		if err != nil {
			errch <- err
		} else {	
			exit <- true
		}
	}()
	<-exit
}
